# -*- coding: utf-8 -*-

import mod.server.extraServerApi as serverApi


from gemstoneScripts.common.gemstonePolishing import *

ServerSystem = serverApi.GetServerSystemCls()
comp = serverApi.GetEngineCompFactory()
levelId = serverApi.GetLevelId()


class Listener(ServerSystem):
    def __init__(self, namespace, system_name):
        super(ServerSystem, self).__init__(namespace, system_name)
        self.ListenEvent()
        pass

    def Destroy(self):
        self.UnListenEvent()
        pass

    def ListenEvent(self):
        self.ListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(),
                            'StartDestroyBlockServerEvent', self, self.try_inlay)
        pass

    def UnListenEvent(self):
        self.UnListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(),
                              'StartDestroyBlockServerEvent', self, self.try_inlay)
        pass

    def try_inlay(self, args):
        block_name = args['blockName']
        if block_name == 'minecraft:anvil':
            player_id = args['playerId']
            comp_item = comp.CreateItem(player_id)
            gemstone = comp_item.GetPlayerItem(1, 0)
            gemstone_name = gemstone['newItemName']
            if gemstone_name in SMOOTH_GEMSTONES:
                slot = comp_item.GetSelectSlotId()
                gemstone_dic = eval(gemstone['extraId'])
                abrasion = gemstone_dic['abrasion']
                enchants = GEMSTONE_ENCHANT[gemstone_name][abrasion]
                mod_enchants = GEMSTONE_MOD_ENCHANT[gemstone_name][abrasion]
                success = False
                for _ in enchants:
                    print _
                    if comp_item.AddEnchantToInvItem(slot, _[0], _[1]):
                        success = True
                for _ in mod_enchants:
                    print _
                    if comp_item.AddModEnchantToInvItem(slot, _[0], _[1]):
                        success = True
                if success:
                    gemstone['count'] -= 1
                    comp_item.SetEntityItem(1, gemstone, 0)
        pass
